const fs = require('fs')
const path = require('path')
const connection = require('../../app/database')
const { AVATAR_PATH } = require('../../app/file-path')

class FileService {

  // 判断用户是否更新头像
  async hasUserAvatar(userId) {
    const statement = `select filename from avatar where userId = ?`
    const result = await connection.execute(statement, [userId])
    return result[0][0]
  }

  // 保存头像信息
  async saveAvatarInfo(filename, mimetype, size, userId) {
    const res = await this.hasUserAvatar(userId) || {}
    let statement = null
    if (res.filename) {
      // 有头像
      statement = `update avatar set filename = ?, mimetype = ?, size = ? where userId = ?`
    } else {
      // 无头像
      statement = `insert into avatar (filename, mimetype, size, userId) values (?, ?, ?, ?)`
    }
    const result = await connection.execute(statement, [filename, mimetype, size, userId])
    res.filename && await fs.unlinkSync(path.resolve(__dirname, `../../../${AVATAR_PATH}/${res.filename}`))
    return result[0]
  }

  // 获取用户头像
  async getAvatarByUserId(userId) {
    const statement = `select * from avatar where userId = ?`
    const [result] = await connection.execute(statement, [userId])
    return result[0]
  }

}

module.exports = new FileService()
